import { get, post, put, deletes } from "./http";
import Apis from "./apilLst";
import { methods } from "@/mixin";
//通用调用
// this.$api({
//   key: 'searchAll',
//   info: { a: 123, b: 456, c: 789, e: 33, d: 0 }, //对应path路径内部的变量map
//   data: { kk: 1 },
//   headers: { a: 1 }
// })
//简单调用
//普通请求
// this.$api('get','searchAll',{})
//path参数
// this.$api('get','searchAll:这里写id的值',{})
//多个path参数
// this.$api("get", "searchAll:[id|id参数值,id2|id2参数值]", {});
function $api(method, keys, params = {}, config) {
  //区分接口上下文分隔符 规则为：页面path/path内api文件中接口名
  let symbol = "/";
  if (typeof method === "object") {
    keys = { ...method };
    method = keys.method;
  }
  let info = "",
    key = "",
    // url = Apis[keys];
    //普通请求
    url = methods.$tryJson.bind(Apis)(keys, symbol);
  //通用调用
  if (typeof keys === "object") {
    if (config) {
      config = Object.assign(keys, config);
    } else {
      config = { ...keys };
    }
    key = keys["key"];
    let { info } = keys;
    if (keys.hasOwnProperty.call("url")) {
      url = keys.url;
    } else {
      if (key) {
        // url = Apis[key];
        url = methods.$tryJson.bind(Apis)(key, symbol);
        if (info) {
          Object.keys(info).forEach((p) => {
            let val = info[p];
            url = url.replace(new RegExp(`{(${p})}`), val);
          });
          // for (let p in info) {
          //   let val = info[p];
          //   url = url.replace(new RegExp(`{(${p})}`), val);
          // }
        }
      }
    }
  } else if (typeof keys === "string") {
    //简单写法
    if (keys.indexOf(":") !== -1) {
      key = keys.split(":")[0];
      info = keys.split(":")[1];
      // url = Apis[key];
      url = methods.$tryJson.bind(Apis)(key, symbol);
      if (/(\[.+\])/.test(info)) {
        //多个path参数
        //"keys:['key|val']"
        let arr = JSON.parse(info);
        arr.forEach((v) => {
          let org = v.split("|");
          let key = org[0];
          let val = org[1];
          url = url.replace(new RegExp(`{(${key})}`), val);
        });
      } else {
        //"keys:info"
        //将接口的path参数传入url模板中
        if (url && url.match(/\{(\w+)\}/gi)) {
          //path参数
          url = url.replace(/\{(\w+)\}/gi, function (val) {
            if (val[val.length - 1] === "/") {
              return info + "/";
            } else {
              return info;
            }
          });
        } else {
          //url模板没有配置path参数但是传入了path参数则拼在url最后面
          url = `${Apis[key]}/${info}`;
        }
      }
    }
  }
  if (!url) {
    return Promise.reject(`请求地址为空或key不正确！`);
  }
  switch (method) {
    case "get":
      return get(url, params, "", config);
    case "post":
      return post(url, params, "", config);
    case "put":
      return put(url, params, "", config);
    case "delete":
      return deletes(url, params, "", config);
    default:
      console.error(`请求方式 ${method} 类型错误`);
      break;
  }
}

export default $api;
